package dragon.controller;

import dragon.verification.Constants;
import dragon.verification.VerificationCode;
import dragon.verification.VerificationCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author: Leo
 * @Date: 2020/2/6 17:28
 */
@RestController
public class CommonController {

    @RequestMapping("/test")
    public String test(){
        return "success";
    }

    /**
     * 生成验证码图片
     * @param request
     * @param response
     */
    @RequestMapping("/login/verificateCode")
    public void createCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //生成验证码
        VerificationCodeUtils codeUtils = new VerificationCodeUtils();
        BufferedImage image = codeUtils.getImage();
        VerificationCode verificationCode = new VerificationCode(codeUtils.getText(), image, Constants.CODE_EXPIRED_SECONDS);
        //把验证码写入到session中
        HttpSession session = request.getSession();
        /*这里注意，如果把session存到redis中的话，这里不要存verificationCode，
        因为redis要求类继承Serializable接口，但是图片BufferedImage并没有继承
        因此可以把VerificationCode拆分成父类和子类，父类继承Serializable接口，有code和过期日
        子类在父类的基础上有BufferedImage,session存父类
        */
        session.setAttribute(Constants.VERIFICATION_CODE,verificationCode);
        //将图片写入到response
        ImageIO.write(image,Constants.JPEG,response.getOutputStream());
    }

    @RequestMapping("/invalidSession")
    public String invalidSession(){
        return "session过期了，请重新登录";
    }
}
